package com.tv.nextin;

import java.util.ArrayList;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.tv.nextin.Utils.Common;
import com.tv.nextin.Utils.KeyboardHelper;
import com.tv.nextin.Utils.Utils;
import com.tv.nextin.adapter.ListBussinessAdapter;
import com.tv.nextin.bean.Bussiness;
import com.tv.nextin.bean.Category;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BussinessListActivity extends Activity implements OnClickListener, OnTouchListener, LocationListener {
	
	TextView title;
	ImageButton btnBack;
	Category category = new Category();
	ListView listBussiness;
	ListBussinessAdapter adapter;
	
	ArrayList<Bussiness> bussinesses = new ArrayList<Bussiness>();
	
	Button btnDistance, btnGetNextin;
	
	ViewGroup main;
	private BroadcastReceiver mReceiver;
	
	private GoogleMap googleMap;
	Location location;
	double mLatitude;
	double mLongitude;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bussiness_list);
		
		main = (ViewGroup)findViewById(R.id.main);
		
		KeyboardHelper.setupUI(BussinessListActivity.this, main);
		
		title = (TextView) findViewById(R.id.title);
		btnBack = (ImageButton) findViewById(R.id.btn_back);
		btnBack.setVisibility(View.VISIBLE);
		
		btnDistance = (Button) findViewById(R.id.btn_distance);
		btnGetNextin = (Button) findViewById(R.id.btn_getnextin);
		
		category = getIntent().getParcelableExtra("category");

		setDataDemo();
		
		listBussiness = (ListView) findViewById(R.id.list_bussiness);
		adapter = new ListBussinessAdapter(BussinessListActivity.this, bussinesses);
		listBussiness.setAdapter(adapter);
		
		setFont();
		init();
		
		listBussiness.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				Intent t = new Intent(BussinessListActivity.this, DetailBussinessActivity.class);
				t.putExtra("bussiness", bussinesses.get(position));
				startActivity(t);
				overridePendingTransition(R.anim.trans_left_in, R.anim.over_main_left);
			}
			
		});
		
		receiverBroastCast();
		// Getting status
		int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
		// Showing status
		if (status == ConnectionResult.SUCCESS) {
			setUpMap();
			focusLocation();
		} else {
			Toast.makeText(BussinessListActivity.this,
					"Google Play Services are not available",
					Toast.LENGTH_SHORT).show();
			int requestCode = 10;
			Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
					requestCode);
			dialog.show();
		}
		
	}
	
	void gotoDetailBussiness(){
		
		
	}
	
	ArrayList<Bussiness> setDataDemo(){
		bussinesses.add(new Bussiness("Bách Khoa", "1.2Km", "Hà Nội", "9.00am | 12.00 pm"));
		bussinesses.add(new Bussiness("Capture Mouse", "1.2Km", "Hà Nội", "9.00am | 12.00 pm"));
		bussinesses.add(new Bussiness("Lotte", "1.2Km", "Hà Nội", "9.00am | 12.00 pm"));
		bussinesses.add(new Bussiness("Good Garden", "1.2Km", "Hà Nội", "9.00am | 12.00 pm"));
		bussinesses.add(new Bussiness("Time City", "1.2Km", "Hà Nội", "9.00am | 12.00 pm"));
		bussinesses.add(new Bussiness("Vincom", "1.2Km", "Hà Nội", "9.00am | 12.00 pm"));
		bussinesses.add(new Bussiness("Royal City", "1.2Km", "Hà Nội", "9.00am | 12.00 pm"));
		bussinesses.add(new Bussiness("Tràng Tiền Plaza", "1.2Km", "Hà Nội", "9.00am | 12.00 pm"));
		bussinesses.add(new Bussiness("Hoàn Kiếm", "1.2Km", "Hà Nội", "9.00am | 12.00 pm"));
		bussinesses.add(new Bussiness("Hồ Tây", "1.2Km", "Hà Nội", "9.00am | 12.00 pm"));
		return bussinesses;
	}
	
	void setFont(){
//		title.setTypeface(Utils.getTypefaceMedium(BussinessListActivity.this));
		btnDistance.setTypeface(Utils.getTypefaceRegular(BussinessListActivity.this));
		btnGetNextin.setTypeface(Utils.getTypefaceRegular(BussinessListActivity.this));
	}
	
	void init(){
		title.setText(category.getName());
		btnBack.setOnTouchListener(this);
		btnDistance.setOnTouchListener(this);
		btnGetNextin.setOnTouchListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			finish();
			break;

		default:
			break;
		}
	}

	
	void closeActivity(){
		finish();
		overridePendingTransition(R.anim.over_main_right, R.anim.trans_right_out);
	}
	
	
	@Override
	public void onBackPressed() {
		closeActivity();
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.btn_back:
			if (event.getAction() == MotionEvent.ACTION_UP){
				closeActivity();
			}
			break;
		case R.id.btn_distance:
			if (event.getAction() == MotionEvent.ACTION_UP){
				Toast.makeText(BussinessListActivity.this, "Sort by distance", Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.btn_getnextin:
			if (event.getAction() == MotionEvent.ACTION_UP){
				Toast.makeText(BussinessListActivity.this, "How is the function?", Toast.LENGTH_SHORT).show();
			}
			break;

		default:
			break;
		}
		return false;
	}
	
	void receiverBroastCast(){
		IntentFilter intentFilter = new IntentFilter();
		
		
		 intentFilter.addAction(Common.FINISH);
		    
		    mReceiver = new BroadcastReceiver() {
				
				@Override
				public void onReceive(Context context, final Intent intent) {
					String action = intent.getAction();
					if (action.equals(Common.FINISH)){
						finish();
					} 
				}
			};
			// register
			this.registerReceiver(mReceiver, intentFilter);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(mReceiver);
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
	
	@SuppressLint("NewApi")
	private void setUpMap() {
		// Do a null check to confirm that we have not already instantiated the
		// map.
		if (googleMap == null) {
			// Try to obtain the map from the SupportMapFragment.
			googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
//			googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

			// Check if we were successful in obtaining the map.

			// Enabling MyLocation in Google Map
			googleMap.setMyLocationEnabled(true);
			googleMap.getUiSettings().setMyLocationButtonEnabled(true);

			/*
			 * // Creating an instance of MarkerOptions MarkerOptions
			 * markerOptions = new MarkerOptions();
			 * 
			 * // Setting position for the marker markerOptions.position(new
			 * LatLng(mLatitude, mLongitude));
			 * 
			 * // Setting custom icon for the marker
			 * markerOptions.icon(BitmapDescriptorFactory
			 * .fromResource(R.drawable.my_location));
			 * 
			 * // Adding the marker to the map
			 * googleMap.addMarker(markerOptions);
			 * 
			 * googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {
			 * 
			 * @Override public boolean onMarkerClick(Marker marker) { return
			 * false; } });
			 */
			// Getting LocationManager object from System Service
			// LOCATION_SERVICE
			LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

			// Creating a criteria object to retrieve provider
			Criteria criteria = new Criteria();

			// Getting the name of the best provider
			String provider = locationManager.getBestProvider(criteria, true);

			// Getting Current Location From GPS

			location = locationManager.getLastKnownLocation(provider);

			if (location != null) {
				onLocationChanged(location);
			}

			locationManager.requestLocationUpdates(provider, 20000, 0,
					new android.location.LocationListener() {

						@Override
						public void onStatusChanged(String provider,
								int status, Bundle extras) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onProviderEnabled(String provider) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onProviderDisabled(String provider) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onLocationChanged(Location location) {
						}
					});
		}

		googleMap.setInfoWindowAdapter(new InfoWindowAdapter() {

			@Override
			public View getInfoWindow(Marker marker) {
				return null;
			}

			@Override
			public View getInfoContents(Marker marker) {
				return null;
			}
		});

	}
	
	void focusLocation() {
		try {
			mLatitude = (float) location.getLatitude();
			mLongitude = (float) location.getLongitude();
			LatLng latLng = new LatLng(mLatitude, mLongitude);

			Log.i("DATA", "LAT: " + mLatitude + "LONG: " + mLongitude);

			googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
			googleMap.animateCamera(CameraUpdateFactory.zoomTo(10));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
}
